package com.umeox.watch.alphabetlearning

import android.animation.ObjectAnimator
import android.content.Intent
import android.content.res.Resources
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import java.util.*

class MainActivity : AppCompatActivity() {

    companion object {

        const val MSG_START_BUBBLE = 0x100

        val BUBBLE_DATA_ARRAY = intArrayOf(
            0,
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10,
            11,
            12,
            13,
            14,
            15,
            16,
            17,
            18,
            19,
            20,
            21,
            22,
            23,
            24,
            25,
            26,
            27
        )
    }

    private lateinit var mRootView: FrameLayout

    private var dataArray: IntArray = BUBBLE_DATA_ARRAY


    private val mHandler = Handler { msg ->
        if (msg.what == MSG_START_BUBBLE) {
            startBubbleAnim()
        }
        true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mRootView = findViewById(R.id.root_view)

        startBubbleAnim()
    }

    private fun startBubbleAnim() {
        if (dataArray.isEmpty()) {
            dataArray = BUBBLE_DATA_ARRAY
            mHandler.sendEmptyMessageDelayed(MSG_START_BUBBLE, 2000)
            return
        }

        val bubbleView = createView()
        val upAnimator = ObjectAnimator.ofFloat(bubbleView, "translationY", 0F, -626F)
            .setDuration(10000)
        upAnimator.start()
        mHandler.sendEmptyMessageDelayed(MSG_START_BUBBLE, 3000)
    }

    private fun createView(): View {

        val frameLayout = FrameLayout(this)
        val layoutParamsForFrameLayout = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            dp2px(386F)
        )
        layoutParamsForFrameLayout.topMargin = 240
        frameLayout.layoutParams = layoutParamsForFrameLayout
        val randomIntArray = getRandomArray(4)
        Log.e("TAG", "randomIntArray=${randomIntArray.contentToString()}")
        for (i in randomIntArray?.indices!!) {
            val imageView = ImageView(this)
            imageView.setImageResource(getBubbleResourceId(randomIntArray[i]))
            imageView.contentDescription = randomIntArray[i].toString()
            val layoutParamsForImageView = FrameLayout.LayoutParams(dp2px(72F), dp2px(250F))
            when (i) {
                0 -> {
                    layoutParamsForImageView.topMargin = dp2px(75F)
                    layoutParamsForImageView.marginStart = dp2px(12F)
                }
                1 -> {
                    layoutParamsForImageView.topMargin = dp2px(22F)
                    layoutParamsForImageView.marginStart = dp2px(91F)
                }
                2 -> {
                    layoutParamsForImageView.topMargin = dp2px(84F)
                    layoutParamsForImageView.marginStart = dp2px(168F)
                }
                else -> {
                    layoutParamsForImageView.topMargin = dp2px(147F)
                    layoutParamsForImageView.marginStart = dp2px(95F)
                }
            }

            imageView.layoutParams = layoutParamsForImageView
            imageView.setOnClickListener {
                Log.e("TAG", "value=" + it.contentDescription)
                val intent = Intent(this@MainActivity,LearningActivity::class.java)
                intent.putExtra("current_index",it.contentDescription.toString().toInt())
                startActivity(intent)

            }
            frameLayout.addView(imageView)
        }

        mRootView.addView(frameLayout)

        return frameLayout
    }

    private fun getBubbleResourceId(i: Int): Int {
        return resources.getIdentifier(
            "alphabet_bubble${i + 1}",
            "drawable",
            packageName
        )
    }


    /**
     * 使用一个List来保存数组，每次随机取出一个移除一个。
     */
    @Synchronized
    private fun getRandomArray(n: Int): IntArray? {
        val random = Random()
        // 当取出的元素个数大于数组的长度时，返回null
        if (n > dataArray.size) {
            return null
        }
        val result = IntArray(n)
        for (i in 0 until n) {
            // 去一个随机数，随机范围是list的长度
            val index: Int = random.nextInt(dataArray.size)
            result[i] = dataArray[index]
            dataArray = removeTarget(dataArray, dataArray[index])
        }
        return result
    }

    private fun removeTarget(array: IntArray, target: Int): IntArray {
        return array
            .filter { it != target }
            .toIntArray()
    }


    private fun dp2px(dp: Float): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics)
            .toInt()
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacksAndMessages(null)
    }

}
